import cv2
import cv_imread as cm
import numpy as np


def gray(img_path):
    # img = cv2.imread(img_path)
    img = cm.cv_imread(img_path)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    save_path = "./deal_image/gray.jpg"
    # cv2.imwrite(save_path, img_gray)
    result = cm.cv_imwrite(save_path, img_gray)
    if result:
        print("保存成功")
        return save_path
    else:
        print("保存失败")


def fu_diao(img_path):
    # img = cv2.imread(img_path)
    img = cm.cv_imread(img_path)
    h, w, _ = img.shape
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_FuDiao = np.zeros_like(img)
    for i in range(h):
        for j in range(w - 2):
            p0 = img_gray[i, j]
            p2 = img_gray[i, j + 2]
            newP = p0 - p2 + 150
            if newP < 0:
                newP = 0
            elif newP > 255:
                newP = 255
            img_FuDiao[i, j] = newP
    save_path = "./deal_image/fu_diao.jpg"
    # cv2.imwrite(save_path, img_FuDiao)
    result = cm.cv_imwrite(save_path, img_FuDiao)
    if result:
        print("保存成功")
        return save_path
    else:
        print("保存失败")



def binary(img_path, item):
    # img = cv2.imread(img_path)
    img = cm.cv_imread(img_path)
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img_binary = np.zeros_like(img)
    if item == "二值化阈值处理":
        ret, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    elif item == "反二值化阈值处理":
        ret, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
    elif item == "截断阈值处理":
        ret, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_TRUNC | cv2.THRESH_OTSU)
    elif item == "低于阈值归零处理":
        ret, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_TOZERO | cv2.THRESH_OTSU)
    elif item == "高于阈值归零处理":
        ret, img_binary = cv2.threshold(img_gray, 0, 255, cv2.THRESH_TOZERO_INV | cv2.THRESH_OTSU)

    save_path = "./deal_image/" + item + ".jpg"
    # cv2.imwrite(save_path, img_binary)
    # return save_path
    result = cm.cv_imwrite(save_path, img_binary)
    if result:
        print("保存成功")
        return save_path
    else:
        print("保存失败")
